package com.seata.simples.common.filter;


import io.seata.core.context.RootContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/11/6 13:12
 * @description
 * @Modify By：
 * @ModifyTime： 2019/11/6
 * @Modify marker：
 **/
@Component
public class SeataFilter implements Filter {
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        String xid=req.getHeader(RootContext.KEY_XID).toLowerCase();
        boolean isBind=false;
        if(StringUtils.isNotBlank(xid)){
            RootContext.bind(xid);
            isBind=true;
        }
        try{
            filterChain.doFilter(servletRequest,servletResponse);
        }finally {
            if(isBind){
                RootContext.unbind();
            }
        }
    }
}
